package com.mounting.wechat.modules.mp.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONValidator;
import com.mounting.wechat.modules.mp.entity.WxMpMessage;
import com.mounting.wechat.modules.mp.entity.WxMpOutMessage;
import com.mounting.wechat.modules.mp.service.WechatMpService;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


/**
 * @author : lianghanmao
 * @date : 2022/11/17
 * 微信公众号微信回调
 */
@RestController
@CommonsLog
public class WechatMpController {

    @Resource
    private WechatMpService wechatMpService;


    /**
     * 消息处理
     * @param requestBody
     * @return
     */
    @PostMapping("/v1/mp/callback")
    public String message(@RequestBody String requestBody, HttpServletRequest request) {
        // 获取appid
        String appid = request.getHeader("x-wx-appid");
        // 不是json
        if (!JSONValidator.from(requestBody).validate()){
            throw new RuntimeException("非法传参");
        }
        JSONObject jsonObject = JSONObject.parseObject(requestBody);
        String msgType = jsonObject.getString("MsgType");
        log.info("消息类型："+ msgType);

        WxMpMessage wxMpMessage = JSONObject.toJavaObject(jsonObject, WxMpMessage.class);
        log.info("requestBody："+ wxMpMessage.toString());

        String wxMpOutMessage = wechatMpService.passivelySendMessages(wxMpMessage);
        log.info("responseBody ："+ wxMpOutMessage);
        return wxMpOutMessage;
    }

}
